<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Hash;
use DB;

class UserController extends Controller
{
    //add
    public function add()
    {
    	return view('admin.user.add');
    }

    //insert
    public function insert(Request $request)
    {
    	$this -> validate($request,[
    		'name' => 'required|min:3|max:18',
    		'password' => 'required',
    		'repassword' => 'required|same:password',
    		'email' => 'email|unique:users',
    		'pic' => 'image',
    		],[
    		'name.required' => '用户名不能为空',
    		'name.min' => '用户名不能小于3个字符',
    		'name.max' => '用户名不能大于18个字符',
    		'password.required' => '密码不能为空',
    		'repassword.required' => '两次密码不一致',
    		'repassword.same' => '两次密码不一致',
    		'email.email' => '邮箱格式不合法',
    		'pic.image' => '图片格式不合法',
            'email.unique' => '该邮箱已被注册',
    		]);
    	$data = $request -> except('_token','repassword');

    	//处理图片
    	if($request -> hasFile('pic'))
    	{
    		if($request -> file('pic') -> isValid())
    		{
    			//获取图片扩展名
    			$extension = $request -> file('pic') -> getClientOriginalExtension();

    			//拼接图片名称
    			$fileName = str_random(32).'.'.$extension;
    			$dir = './uploads/imgs/';

    			//判断目录是否存在
    			if(!file_exists($dir))
    			{
    				mkdir($dir,0777,true);
    			}

    			//移动
    			$move = $request -> file('pic') -> move($dir,$fileName);

    			//判断是否移动成功
    			if($move)
    			{
    				$data['pic'] = $fileName;
    				
    			}
    		}
    	}

    	//准备数据
    	$data['remember_token'] = str_random(50);

    	//获取当前时间戳
    	$time = time();
    	$data['add_time'] = $time;
    	$data['update_time'] = $time;

    	//密码加密
    	$password = hash::make($data['password']);
    	$data['password'] = $password;
    
    	//添加数据至数据库
    	$res = DB::table('users') -> insert($data);

    	//判断是否添加成功
    	if($res)
    	{
    		return redirect('/admin/user/index') -> with(['info' => '添加成功']);
    	}else
    	{
    		return back() -> with(['info' => '添加失败']);
    	}

    }


    //index
    public function index(Request $request)
    {
    	$num = $request -> input('num',10);
    	$keyword = $request -> input('keyword','');
    	$data = DB::table('users') -> where('name','like','%'.$keyword.'%') -> where('auth','<',8)-> paginate($num);
    	return view('admin.user.index',['data' => $data,'request' => $request -> all()]);
    }

    public function ajaxChangeName(Request $request)
    {
        $data = $request -> all();
        $res = DB::table('users') -> where('name',$data['name']) -> first();
        if($res)
        {
            return response() -> json(0);
        }else
        {
            $r = DB::table('users') -> where('id',$data['id']) -> update(['name' => $data['name']]);
            if($r)
            {
                return response() -> json(1);
            }else
            {
                return response() -> json(2);
            }
        }
    }

    public function edit($id)
    {
        $data = DB::table('users') -> where('id',$id) -> first();
        return view('admin.user.edit',['data' => $data]);
    }

    //update
    public function update(Request $request,$id)
    {
        $this -> validate($request,[
            'name' => 'required|min:3|max:18',
            'password' => 'required',
            'repassword' => 'required|same:password',
            'email' => 'email',
            'pic' => 'image',
            ],[
            'name.required' => '用户名不能为空',
            'name.min' => '用户名不能小于3个字符',
            'name.max' => '用户名不能大于18个字符',
            'password.required' => '密码不能为空',
            'repassword.required' => '两次密码不一致',
            'repassword.same' => '两次密码不一致',
            'email.email' => '邮箱格式不合法',
            'pic.image' => '图片格式不合法',
            ]);

        $data = $request -> except('_token','repassword');
        $oldPic = DB::table('users') -> where('id',$id) -> first() -> pic;
        $oldPath = './uploads/imgs/'.$oldPic;

        $time = time();
        $data['update_time'] = $time;
        $data['password'] = hash::make($data['password']);

        //处理图片
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                //获取图片扩展名
                $extension = $request -> file('pic') -> getClientOriginalExtension();

                //拼接图片名称
                $fileName = str_random(32).'.'.$extension;
                $dir = './uploads/imgs/';

                //判断目录是否存在
                if(!file_exists($dir))
                {
                    mkdir($dir,0777,true);
                }

                //移动
                $move = $request -> file('pic') -> move($dir,$fileName);

                //判断是否移动成功
                if($move)
                {
                    $data['pic'] = $fileName;
                    
                }
            }
        }

        $res = DB::table('users') -> where('id',$id) -> update($data);
        if($res)
        {
            if(file_exists($oldPath))
            {
               unlink($oldPath); 
            }
            
            return redirect('admin/user/index') -> with(['info' => '更新成功']);
        }else
        {
            return redirect('admin/user/index') -> with(['info' => '更新失败']);
        }
    }

    public function delete($id)
    {
        $res = DB::table('users') -> delete($id);
        if($res)
        {
            return redirect('/admin/user/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }
}
